package org.west.sky.frame.activiti.study.chapter14;

import lombok.SneakyThrows;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.west.sky.frame.activiti.study.chapter14.demo0102.Calculation;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * author: chz
 * date: 2025/3/12
 * description: 服务任务-属性注入
 */
public class RunDemo14_1_2 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo14_1_2 runDemo13_1_1 = new RunDemo14_1_2();
        runDemo13_1_1.deploy();
    }

    @SneakyThrows
    private void deploy() {
//        demo1();
        demo2();
    }

    /**
     * string注入
     */
    private void demo1() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
        //部署流程
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter14/Chapter14_1_2_1.bpmn20.xml");

        Map<String, Object> variables = new HashMap<>();
        variables.put("discountRate", 0.9);
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), variables);

        HistoricVariableInstance totalMoney = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).variableName("totalMoney").singleResult();
        System.out.println("====总金额：" + totalMoney.getValue());
        closeEngine();
    }

    /**
     * 表达式注入
     */
    private void demo2() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
        //部署流程
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter14/Chapter14_1_2_2.bpmn20.xml");

        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("====第一个任务id:" + task.getId() + ",任务名称：" + task.getName());
        Map<String, Object> variables = new HashMap<>();
        variables.put("discount", 0.9);
        variables.put("unitPrice", 100);
        variables.put("quantity", 5);
        variables.put("description", "商品购买");
        variables.put("calculationBean", new Calculation());
        taskService.complete(task.getId(), variables);

        HistoricVariableInstance totalMoney = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).variableName("totalMoney").singleResult();
        System.out.println("====总金额：" + totalMoney.getValue());
        closeEngine();
    }
}
